import store from '../store'
// 使用绝对URL引用音频文件，以避免文件加载问题
const tipAudioUrl = process.env.NODE_ENV === 'development' ? './static/audio/tip.wav' : '/static/audio/tip.wav'
// 导入托盘管理器
import trayManager from './tray-manager'
// 导入API
import { userApi } from './api'

let websocket = null
let reconnectTimer = null
let heartbeatTimer = null
let userListUpdateTimer = null
const heartbeatInterval = 30000 // 30秒发送一次心跳
const reconnectInterval = 5000 // 5秒尝试重连一次
const userListUpdateInterval = 20000 // 20秒更新一次用户列表
let messageSound = null
let audioContext = null

// 初始化音频上下文
const initAudioContext = () => {
  try {
    // 创建音频上下文
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new AudioContext();
    
    // 添加自动恢复音频上下文的事件监听
    const resumeAudioContext = async () => {
      if (audioContext && audioContext.state === 'suspended') {
        try {
          await audioContext.resume();
          console.log('用户交互已恢复AudioContext，状态:', audioContext.state);
        } catch (e) {
          console.warn('恢复AudioContext失败:', e);
        }
      }
    };
    
    // 添加事件监听，用户交互时自动恢复AudioContext
    ['click', 'touchend', 'keydown'].forEach(eventType => {
      document.addEventListener(eventType, resumeAudioContext, { once: false });
    });
    
    console.log('音频上下文初始化成功，状态:', audioContext.state);
    return true;
  } catch (e) {
    console.warn('无法创建音频上下文:', e);
    return false;
  }
};

// 初始化HTML5 Audio
const initHtmlAudio = () => {
  try {
    if (!messageSound || !(messageSound instanceof Audio)) {
      messageSound = new Audio();
      messageSound.preload = 'auto';
      
      // 添加自动重试逻辑
      messageSound.addEventListener('error', () => {
        console.warn('音频加载错误，尝试使用备用方式');
        try {
          // 使用更响亮的提示音
          messageSound.src = 'data:audio/wav;base64,UklGRjoEAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YRYEAACAgICAgICAgICAgICAgICAgICC0M/IwMC/v76+vLu6urm5urq7vL2/wcPFx8nMztHS09TU1NXW1dXU1NPR0M7MysnHxcPBv769vLu5uLe2trW1tba2tre4ubq8vcDCxMbIyszOz9HS09TV1tbX19fX19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29vLy7u7q6urq6urq6urq7u7u8vL2+vr+/wMHBwsPExMXGx8fIycnKy8vMzc3Oz8/P0NDR0dHS0tLS09PT09PT09PT09PT09PT0tLS0tHR0dDQ0M/Pzs7NzczLy8rJyMjHxsbFxMTDw8LBwMC/v76+vb28vLu7u7u7u7u7u7u7vLy8vb29vr6/v8DAwcHCw8PExcXGxsfHyMjJycnKy8vMzM3Nzc7Ozs/Pz8/Q0NDQ0NDQ0NDQ0NDQ0M/Pz8/Pzs7Ozc3NzMzMy8vKysnJyMjHx8bGxcXEw8PDwsLBwcC/v76+vr69vb29vLy8vLy8vLy8vLy8vb29vb6+vr+/wMDAwcHCwsLDxMTExcXGxsbHx8fIyMnJycnKysrLy8vLzMzMzMzMzMzMzMzMzMzMzMzMy8vLy8vKysrKycnJyMjIx8fHxsbGxcXFxMTDw8PCwsLBwcDAwL+/v76+vr6+vr6+vb29vby8vLy8vLy8vL29vb29vr6+vr6/v7+/wMDAwcHBwcLCwsLDw8PExMTExcXFxcXGxsbGxsbHx8fHx8fHx8fHx8fHx8fHx8fGxsbGxsbGxcXFxcXFxMTExMTDw8PDw8PCwsLCwcHBwcDAwMC/v7+/v7+/v7+/v7+/v7+/v7+/vr6+vr6+vr6+vr6+vr6+vr6+vr6/v7+/v7+/v7+/v8DAwMDAwMDAwMDAwMDBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwMDAwMDAwMDAwMC/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v8A=';
          messageSound.load();
        } catch (e) {
          console.error('加载备用音频失败:', e);
        }
      });
      
      console.log('HTML5 Audio对象初始化成功');
    }
    return true;
  } catch (e) {
    console.error('初始化HTML5 Audio失败:', e);
    return false;
  }
};

// 预加载音频数据
const preloadAudio = async () => {
  try {
    // 创建HTML5 Audio对象（如果不存在）
    if (!messageSound || !(messageSound instanceof Audio)) {
      initHtmlAudio();
    }
    
    // 重置Audio状态
    if (messageSound instanceof Audio) {
      // 确保设置新的src前先暂停
      try {
        messageSound.pause();
      } catch (e) {
        // 忽略可能的错误
      }
      
      console.log('开始加载音频文件到HTML5 Audio...');
      // 设置成功和失败处理函数
      return new Promise((resolve, reject) => {
        const onCanPlay = () => {
          messageSound.removeEventListener('canplaythrough', onCanPlay);
          messageSound.removeEventListener('error', onError);
          console.log('音频文件加载成功');
          resolve(messageSound);
        };
        
        const onError = (e) => {
          messageSound.removeEventListener('canplaythrough', onCanPlay);
          messageSound.removeEventListener('error', onError);
          console.warn('音频加载失败:', e);
          
          // 尝试使用备用音频
          try {
            console.log('尝试加载备用音频...');
            // 使用更响亮的提示音
            messageSound.src = 'data:audio/wav;base64,UklGRjoEAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YRYEAACAgICAgICAgICAgICAgICAgICC0M/IwMC/v76+vLu6urm5urq7vL2/wcPFx8nMztHS09TU1NXW1dXU1NPR0M7MysnHxcPBv769vLu5uLe2trW1tba2tre4ubq8vcDCxMbIyszOz9HS09TV1tbX19fX19fW1tXU09LQz87My8nIxsXDwcC+vby7urm4t7e2tra2tre3uLm6u72+wMHDxcfJysvNz9DR0tPU1dbW19fY2NjY2NjX19bW1dTT0tHPzs3LysjHxcTCwL++vby7urm4uLe3t7e3t7e4uLm6u7y+v8HCxMXHycrMzc/Q0dLT1NXV1tfX2NjZ2dnZ2dnY2NjX1tbV1NPS0dDOzcvKyMfFxMPBwL69vLu6ubm4t7e3t7e3t7e4uLm6u7y9v8DBw8TGx8nLzM3P0NHS09TV1dbX19jY2dnZ2tra2tra2djY19fW1dTT0tHQz87NzMrJx8bFw8LAvr68u7q5uLi3t7e3t7e3t7i4ubq7vL2+v8HCw8XGy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xMTExcXGxsbHx8fIyMnJycnKysrLy8vLzMzMzMzMzMzMzMzMzMzMzMzMy8vLy8vKysrKycnJyMjIx8fHxsbGxcXFxMTDw8PCwsLBwcDAwL+/v76+vr6+vr6+vb29vby8vLy8vLy8vL29vb29vr6+vr6/v7+/wMDAwcHBwcLCwsLDw8PExMTExcXFxcXGxsbGxsbHx8fHx8fHx8fHx8fHx8fHx8fGxsbGxsbGxcXFxcXFxMTExMTDw8PDw8PCwsLCwcHBwcDAwMC/v7+/v7+/v7+/v7+/v7+/v7+/vr6+vr6+vr6+vr6+vr6+vr6+vr6/v7+/v7+/v7+/v8DAwMDAwMDAwMDAwMDBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwMDAwMDAwMDAwMC/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v8A=';
            resolve(messageSound);
          } catch (e2) {
            reject(e2);
          }
        };
        
        messageSound.addEventListener('canplaythrough', onCanPlay, { once: true });
        messageSound.addEventListener('error', onError, { once: true });
        
        // 超时处理
        const timeoutId = setTimeout(() => {
          messageSound.removeEventListener('canplaythrough', onCanPlay);
          messageSound.removeEventListener('error', onError);
          console.warn('音频加载超时');
          
          // 无论如何，返回messageSound对象
          resolve(messageSound);
        }, 3000);
        
        // 设置音频源
        messageSound.src = tipAudioUrl;
        messageSound.load();
      });
    }
    
    return null;
  } catch (e) {
    console.error('预加载音频出错:', e);
    return null;
  }
};

// 播放提示音
const playNotificationSound = async () => {
  console.log('尝试播放提示音...');
  
  try {
    // 始终首先尝试使用AudioContext生成提示音，这种方式更加可靠
    if (audioContext) {
      console.log('直接使用AudioContext生成提示音');
      
      // 如果音频上下文处于暂停状态，尝试恢复
      if (audioContext.state === 'suspended') {
        try {
          await audioContext.resume();
          console.log('AudioContext恢复成功');
        } catch (e) {
          console.warn('恢复AudioContext失败:', e);
        }
      }
      
      try {
        // 创建更明显的双音提示音
        const currentTime = audioContext.currentTime;
        
        // 创建振荡器和增益节点
        const oscillator1 = audioContext.createOscillator();
        const oscillator2 = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        // 设置音调参数
        oscillator1.type = 'sine';
        oscillator1.frequency.setValueAtTime(880, currentTime); // A5音
        oscillator1.frequency.setValueAtTime(988, currentTime + 0.15); // B5音
        
        oscillator2.type = 'sine';
        oscillator2.frequency.setValueAtTime(659.25, currentTime); // E5音
        oscillator2.frequency.setValueAtTime(783.99, currentTime + 0.15); // G5音
        
        // 设置音量包络
        gainNode.gain.setValueAtTime(0, currentTime);
        gainNode.gain.linearRampToValueAtTime(0.7, currentTime + 0.03);
        gainNode.gain.setValueAtTime(0.7, currentTime + 0.25);
        gainNode.gain.linearRampToValueAtTime(0, currentTime + 0.3);
        
        // 连接节点
        oscillator1.connect(gainNode);
        oscillator2.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        // 开始和停止播放
        oscillator1.start(currentTime);
        oscillator2.start(currentTime);
        oscillator1.stop(currentTime + 0.3);
        oscillator2.stop(currentTime + 0.3);
        
        console.log('成功播放合成提示音');
        return true;
      } catch (e) {
        console.warn('播放合成提示音失败:', e);
      }
    }
    
    // 如果AudioContext方法失败，尝试使用HTML5 Audio作为备选
    if (messageSound instanceof Audio) {
      console.log('尝试使用HTML5 Audio播放', {
        readyState: messageSound.readyState,
        paused: messageSound.paused,
        volume: messageSound.volume
      });
      
      if (messageSound.readyState >= 2) { // HAVE_CURRENT_DATA or higher
        try {
          console.log('尝试播放HTML5 Audio...');
          // 重置音频位置
          messageSound.currentTime = 0;
          // 增大音量
          messageSound.volume = 1.0;
          await messageSound.play();
          console.log('音频播放成功(HTML5 Audio)');
          return true;
        } catch (e) {
          console.warn('HTML5 Audio播放失败:', e);
        }
      } else {
        console.warn('音频未准备好，正在重新加载...');
        await preloadAudio();
        if (messageSound.readyState >= 2) {
          try {
            // 重置音频位置
            messageSound.currentTime = 0;
            // 增大音量
            messageSound.volume = 1.0;
            await messageSound.play();
            console.log('音频播放成功(HTML5 Audio重新加载)');
            return true;
          } catch (playError) {
            console.warn('重新加载后播放失败:', playError);
          }
        }
      }
    }
    
    console.warn('没有可用的音频播放方式');
    return false;
  } catch (e) {
    console.warn('播放提示音失败:', e);
    return false;
  }
};

// 获取WebSocket连接地址
const getWsUrl = (userId) => {
  // 判断是否在NW.js环境中运行
  const isNwjs = typeof window !== 'undefined' && typeof window.nw !== 'undefined';
  
  // 开发环境或非NW.js环境
  if (process.env.NODE_ENV === 'development' || !isNwjs) {
    return `ws://${window.location.host}/ws/chat/${userId}`;
  }
  
  // 生产环境且在NW.js中
  return `ws://localhost:8080/ws/chat/${userId}`;
};

const plugin = {
  install(Vue) {
    // 初始化音频并预加载
    initAudioContext();
    initHtmlAudio();
    preloadAudio();
    
    // 添加用户交互解锁音频的机制
    const unlockAudio = async () => {
      try {
        console.log('开始解锁音频...');
        
        // 尝试恢复AudioContext
        if (audioContext) {
          if (audioContext.state === 'suspended') {
            try {
              await audioContext.resume();
              console.log('用户交互已解锁AudioContext，当前状态:', audioContext.state);
            } catch (e) {
              console.warn('恢复AudioContext失败:', e);
            }
          } else {
            console.log('AudioContext当前状态:', audioContext.state);
          }
        }
        
        // 尝试播放静音音频来解锁
        if (messageSound instanceof Audio) {
          try {
            // 先设置音量为0，避免用户听到声音
            messageSound.volume = 0;
            messageSound.currentTime = 0;
            
            // 使用await确保播放操作完成
            await messageSound.play();
            console.log('静音音频播放成功');
            
            // 确保音频播放和停止
            setTimeout(() => {
              messageSound.pause();
              messageSound.currentTime = 0;
              messageSound.volume = 1;
              console.log('音频已解锁');
              
              // 确认AudioContext状态
              if (audioContext) {
                console.log('解锁后AudioContext状态:', audioContext.state);
              }
              
              // 尝试播放一个测试声音确认解锁成功
              setTimeout(async () => {
                try {
                  // 使用AudioContext生成短促的测试声音
                  if (audioContext && audioContext.state === 'running') {
                    const testTime = audioContext.currentTime;
                    const testOsc = audioContext.createOscillator();
                    const testGain = audioContext.createGain();
                    
                    testOsc.type = 'sine';
                    testOsc.frequency.value = 440; // A4音
                    
                    // 使用非常小的音量，几乎听不到
                    testGain.gain.setValueAtTime(0, testTime);
                    testGain.gain.linearRampToValueAtTime(0.01, testTime + 0.02);
                    testGain.gain.linearRampToValueAtTime(0, testTime + 0.04);
                    
                    testOsc.connect(testGain);
                    testGain.connect(audioContext.destination);
                    
                    testOsc.start(testTime);
                    testOsc.stop(testTime + 0.05);
                    console.log('测试声音生成成功，音频系统已解锁');
                    
                    // 尝试播放一次正常提示音，但音量非常小
                    setTimeout(() => {
                      try {
                        const confirmGain = audioContext.createGain();
                        confirmGain.gain.value = 0.01; // 非常小的音量
                        
                        // 使用现有的playNotificationSound但音量极小
                        const originalConnect = AudioNode.prototype.connect;
                        AudioNode.prototype.connect = function(destination) {
                          if (destination === audioContext.destination) {
                            return originalConnect.call(this, confirmGain);
                          }
                          return originalConnect.apply(this, arguments);
                        };
                        
                        confirmGain.connect(audioContext.destination);
                        playNotificationSound().then(() => {
                          // 恢复原始connect方法
                          AudioNode.prototype.connect = originalConnect;
                          console.log('确认提示音播放成功，音频系统完全解锁');
                        });
                      } catch (e) {
                        console.warn('确认提示音播放失败', e);
                      }
                    }, 300);
                  } else {
                    console.warn('AudioContext不是running状态，测试声音未播放');
                  }
                } catch (e) {
                  console.warn('播放测试声音失败', e);
                }
              }, 300);
            }, 50);
          } catch (e) {
            messageSound.volume = 1;
            console.warn('初始化音频解锁失败，这可能是因为用户还未与页面交互', e);
          }
        }
      } catch (e) {
        console.warn('解锁音频时出错:', e);
      }
    };
    
    // 将Vue实例暴露为全局引用，方便在handleMessage中访问
    Vue.prototype.$ws = {
      unlockAudio, // 提供音频解锁函数
      // 可以在此添加更多需要暴露的方法
    };
    
    // 添加页面可见性变化监听，恢复音频上下文
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible' && audioContext) {
        audioContext.resume().catch(e => console.warn('恢复AudioContext失败:', e));
      }
    });
    
    // 添加事件监听器
    ['click', 'touchstart', 'keydown'].forEach(event => {
      document.addEventListener(event, unlockAudio, { once: true });
    });
    
    Vue.prototype.$initWebSocket = function(userId) {
      if (websocket) {
        websocket.close()
      }
      
      // 创建WebSocket连接
      const wsUrl = getWsUrl(userId);
      websocket = new WebSocket(wsUrl)
      
      websocket.onopen = () => {
        console.log('WebSocket连接已建立')
        
        // 清除重连定时器
        if (reconnectTimer) {
          clearTimeout(reconnectTimer)
          reconnectTimer = null
        }
        
        // 建立心跳机制
        startHeartbeat()
        
        // 启动用户列表更新
        startUserListUpdate()
      }
      
      websocket.onmessage = (event) => {
        const message = JSON.parse(event.data)
        handleMessage(message)
      }
      
      websocket.onclose = () => {
        console.log('WebSocket连接已关闭')
        
        // 清除心跳定时器
        if (heartbeatTimer) {
          clearInterval(heartbeatTimer)
          heartbeatTimer = null
        }
        
        // 清除用户列表更新定时器
        if (userListUpdateTimer) {
          clearInterval(userListUpdateTimer)
          userListUpdateTimer = null
        }
        
        // 尝试重连
        if (!reconnectTimer) {
          reconnectTimer = setTimeout(() => {
            console.log('正在尝试重新连接WebSocket...')
            Vue.prototype.$initWebSocket(userId)
          }, reconnectInterval)
        }
      }
      
      websocket.onerror = (error) => {
        console.error('WebSocket发生错误:', error)
      }
      
      Vue.prototype.$websocket = websocket
    }
    
    Vue.prototype.$closeWebSocket = function() {
      if (websocket) {
        websocket.close()
        websocket = null
      }
      
      if (heartbeatTimer) {
        clearInterval(heartbeatTimer)
        heartbeatTimer = null
      }
      
      if (userListUpdateTimer) {
        clearInterval(userListUpdateTimer)
        userListUpdateTimer = null
      }
      
      if (reconnectTimer) {
        clearTimeout(reconnectTimer)
        reconnectTimer = null
      }
    }
    
    // 发送消息的方法
    Vue.prototype.$sendMessage = function(message) {
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message))
      } else {
        console.error('WebSocket未连接，无法发送消息')
      }
    }
    
    // 添加播放提示音的方法，可以手动触发
    Vue.prototype.$playNotificationSound = playNotificationSound;
    
    // 添加手动更新用户列表的方法
    Vue.prototype.$updateUserList = updateUserList;
  }
}

// 处理接收到的消息
function handleMessage(data) {
  const messageType = data.type
  const currentUser = store.state.user;
  
  switch (messageType) {
    case 0: // 聊天消息
      store.dispatch('addMessage', data.data)
      
      // 播放提示音和显示通知
      if (currentUser && data.data.senderId !== currentUser.id) {
        // 检查是否启用了声音 - 通过store获取根组件状态
        const vm = store._vm; // 通过store获取Vue实例
        const soundEnabled = vm && vm.$root && 
                          (typeof vm.$root.$data !== 'undefined' && 
                           typeof vm.$root.$data.soundEnabled === 'boolean' ? 
                           vm.$root.$data.soundEnabled : 
                           (localStorage.getItem('soundEnabled') !== 'false')); // 默认开启
        
        // 只有当声音开启时才播放提示音
        if (soundEnabled) {
          playNotificationSound();
        }
        
        // 闪烁标题和托盘图标（不管声音是否开启都执行）
        if (document.hidden) {
          flashTitle();
        }
        
        // 如果窗口最小化或在托盘中，闪烁托盘图标
        trayManager.startFlashTray();
        
        // 如果声音开启并且是私聊消息，尝试显示原生通知
        if (data.data.chatType === 0) {
          const senderName = data.data.senderName || '用户';
          const content = data.data.messageType === 0 ? data.data.content : 
                         (data.data.messageType === 1 ? '[图片]' : '[文件]');
          
          // 只有当声音开启时才显示通知
          if (soundEnabled) {
            try {
              trayManager.showNativeNotification(
                `来自${senderName}的新消息`, 
                content.length > 50 ? content.substring(0, 50) + '...' : content,
                3000 // 指定3秒自动关闭
              );
            } catch (e) {
              console.error('显示通知失败:', e);
            }
          }
        } else if (soundEnabled) { // 群聊消息且声音开启
          const senderName = data.data.senderName || '用户';
          const content = data.data.messageType === 0 ? data.data.content : 
                         (data.data.messageType === 1 ? '[图片]' : '[文件]');
          
          try {
            trayManager.showNativeNotification(
              `群聊新消息`, 
              `${senderName}: ${content.length > 40 ? content.substring(0, 40) + '...' : content}`,
              3000 // 指定3秒自动关闭
            );
          } catch (e) {
            console.error('显示通知失败:', e);
          }
        }
      }
      break
      
    case 1: // 用户上线
      store.dispatch('updateUserStatus', {
        userId: data.data.id,
        online: true
      })
      // 更新用户列表，确保新用户被添加
      updateUserList();
      break
      
    case 2: // 用户下线
      store.dispatch('updateUserStatus', {
        userId: data.data.id,
        online: false
      })
      // 更新用户列表，保证状态同步
      updateUserList();
      break
      
    case 3: // 心跳消息
      console.log('收到心跳响应')
      break
      
    case 4: // 用户列表更新通知
      // 立即更新用户列表
      updateUserList();
      break
      
    default:
      console.warn('收到未知类型的消息:', data)
  }
}

// 开始心跳检测
function startHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
  }
  
  heartbeatTimer = setInterval(() => {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify({
        type: 3, // 心跳消息
        data: null
      }))
    }
  }, heartbeatInterval)
}

// 定期更新用户列表
function startUserListUpdate() {
  if (userListUpdateTimer) {
    clearInterval(userListUpdateTimer)
  }
  
  // 立即执行一次用户列表更新
  updateUserList()
  
  userListUpdateTimer = setInterval(() => {
    updateUserList()
  }, userListUpdateInterval)
}

// 更新用户列表
async function updateUserList() {
  try {
    if (!store.state.user) {
      console.warn('用户未登录，跳过更新用户列表')
      return
    }
    
    const userList = await userApi.getUserList()
    store.dispatch('updateUserList', userList)
    console.log('用户列表已更新，当前用户数:', userList.length)
  } catch (error) {
    console.error('更新用户列表失败:', error)
  }
}

// 闪烁标题提醒
let flashTitleInterval = null
const originTitle = document.title
function flashTitle() {
  if (flashTitleInterval) {
    return
  }
  
  let flashing = false
  flashTitleInterval = setInterval(() => {
    document.title = flashing ? '【新消息】' + originTitle : originTitle
    flashing = !flashing
  }, 500)
  
  // 当用户切换回页面时，恢复原标题
  window.addEventListener('focus', stopFlashTitle)
}

function stopFlashTitle() {
  if (flashTitleInterval) {
    clearInterval(flashTitleInterval)
    flashTitleInterval = null
    document.title = originTitle
  }
  window.removeEventListener('focus', stopFlashTitle)
  
  // 同时停止托盘闪烁
  if (trayManager) {
    trayManager.stopFlashTray();
  }
}

export default plugin 